<template>
    <div class="goods-add-form">
        <!-- 基础信息区域 -->
        <div class="section1">
            <div class="pro_info_title" style="text-align: center;">
                <div
                    style="margin-left: 10px; height: 40px;width: 250px; text-align: center;line-height: 40px;float: left;font-weight: bold;">
                    {{ pro.pro_name }}&nbsp;{{ pro.pro_code }}</div>
                <div
                    style="margin: 0 auto; height: 40px;width: 250px; text-align: center;line-height: 40px;float: right;">
                    <el-button plain @click="handleEdit">编辑</el-button>
                    <el-button plain @click="handleDelete">删除</el-button>
                    <el-button plain @click="handleDeactivate">停用</el-button>
                </div>
            </div>
            <hr>
            <div class="carousel-container" style="margin-left: 0px;">
                <el-carousel trigger="click" height="230px">
                    <el-carousel-item v-for="item in fileList" :key="item.url">
                        <img class="carousel-image" :src="item.url" alt="Preview Image" />
                    </el-carousel-item>
                </el-carousel>
            </div>


            <div class="pro_info_value"
                style="background-color: white; border: 1px solid #eee; font-family: Arial, sans-serif; max-width: 940px; margin: 0 0 0 0 auto;">
                <!-- 顶部价格横条 -->
                <div style="background-color: #e0f7e0; padding: 20px 15px; display: flex;">
                    <span style="color: red; font-weight: bold; margin-right: 30px;">入库参考价：{{ pro.pro_cost_price
                    }}</span>
                    <span style="color: red; font-weight: bold;">出库参考价：{{ pro.pro_sale_price }}</span>
                </div>

                <!-- 商品信息表格 -->
                <table style="width: 100%; border-collapse: collapse; border: none;">
                    <tbody>
                        <!-- 货品类型行 -->
                        <tr>
                            <td style="padding: 10px 15px; width: 15%; color: #666; text-align: center;">产品类型</td>
                            <td style="padding: 10px 10px; width: 20%; text-align: center;">{{
                                typeValue(pro.pro_type_code) }}</td>
                            <td style="padding: 10px 15px; width: 15%; color: #666; text-align: center;">规格型号</td>
                            <td style="padding: 10px 10px; width: 20%; text-align: center;">{{ pro.pro_model }}</td>
                            <td style="padding: 10px 15px; width: 15%; color: #666; text-align: center;">品牌</td>
                            <td style="padding: 10px 10px; width: 20%; text-align: center;">{{ pro.pro_brand }}</td>
                        </tr>
                        <tr>
                            <td style="padding: 10px 15px; width: 15%; color: #666; text-align: center;">产品属性</td>
                            <td style="padding: 10px 10px; width: 20%; text-align: center;">{{
                                attributeValue(pro.pro_attribute_id) }}</td>
                            <td style="padding: 10px 15px; width: 15%; color: #666; text-align: center;">产品单位</td>
                            <td style="padding: 10px 10px; width: 20%; text-align: center;">{{
                                measureValue(pro.measure_id) }}</td>
                            <td colspan="2"></td> <!-- 空列保持对齐 -->
                        </tr>

                        <!-- 价格行 -->
                        <tr>
                            <td style="padding: 10px 15px; width: 15%; color: #666; text-align: center;">销售单价</td>
                            <td style="padding: 10px 10px; width: 20%; text-align: center;">{{ pro.pro_sale_price }}
                            </td>
                            <td style="padding: 10px 15px; width: 15%; color: #666; text-align: center;">成本单价</td>
                            <td style="padding: 10px 10px; width: 20%; text-align: center;">{{ pro.pro_cost_price }}
                            </td>
                            <td style="padding: 10px 15px; width: 15%; color: #666; text-align: center;">销售毛利</td>
                            <td style="padding: 10px 10px; width: 20%; text-align: center;">{{ pro.pro_grossMargin }}
                            </td>
                        </tr>

                        <!-- 状态行 -->
                        <tr>
                            <td style="padding: 10px 15px; width: 15%; color: #666; text-align: center;">状态</td>
                            <td style="padding: 10px 10px; width: 20%; text-align: center;">{{ pro_status == 0 ? "正常" :
                                "停用" }}</td>
                            <td style="padding: 10px 15px; width: 15%; color: #666; text-align: center;">排序</td>
                            <td style="padding: 10px 10px; width: 20%; text-align: center;">{{ pro.pro_sort }}</td>
                            <td colspan="2"></td> <!-- 空列保持对齐 -->
                        </tr>

                        <!-- 时间行 -->
                        <tr>
                            <td style="padding: 10px 15px; width: 15%; color: #666; text-align: center;">创建人</td>
                            <td style="padding: 10px 10px; width: 20%; text-align: center;">{{ pro.create_by }}</td>
                            <td style="padding: 10px 15px; width: 15%; color: #666; text-align: center;">创建时间</td>
                            <td style="padding: 10px 10px; width: 20%; text-align: center;">{{
                                pro.create_time.replace('T', ' ') }}</td>
                            <td colspan="2"></td>
                        </tr>
                        <tr>
                            <td style="padding: 10px 15px; width: 15%; color: #666; text-align: center;">修改人</td>
                            <td style="padding: 10px 10px; width: 22%; text-align: center;">{{ pro.update_by === 'null'
                                ? '暂无' : pro.update_by }}</td>
                            <td style="padding: 10px 15px; width: 15%; color: #666; text-align: center;">修改时间</td>
                            <td style="padding: 10px 10px; width: 22%; text-align: center;">{{
                                pro.update_time === 'null' ? '暂无' : pro.update_time.replace('T', ' ') }}</td>
                            <td colspan="2"></td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="pro_info_value2"
                style="display: flex; font-family: Arial, sans-serif;border-radius: 4px;box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);">
                <!-- 库存数量 -->
                <div style="width: 115px; height: 70px; background-color: #f5f5f5; text-align: center;">
                    <p style="font-size: 20px; font-weight: bold; margin: 5px 0; color: #333;">{{ stock_numder }}{{
                        measureValue(pro.measure_id) }}</p>
                    <p style="font-size: 14px; color: #666; margin: 0;">总库存</p>
                </div>

                <!-- 库存金额 -->
                <div style="width: 115px; height: 70px; background-color: #f5f5f5; text-align: center;">
                    <p style="font-size: 20px; font-weight: bold; margin: 10px 0px 5px 0px; color: #333;">{{
                        pro_sale_total }}</p>
                    <p style="font-size: 14px; color: #666; margin: 0;">库存总金额</p>
                </div>
            </div>
        </div>

        <div class="section">
            <el-menu mode="horizontal" :default-active="activeMenu" @select="handleMenuSelect" class="inventory-menu"
                :ellipsis="false">
                <!-- <el-menu-item index="other">其他信息</el-menu-item> -->
                <el-menu-item index="inventory">库存信息</el-menu-item>
                <!-- <el-menu-item index="inbound">入库记录</el-menu-item> -->
                <el-menu-item index="qty">盘点记录</el-menu-item>
                <el-menu-item index="trf">调拨记录</el-menu-item>
                <el-menu-item index="purchase">采购记录</el-menu-item>
                <el-menu-item index="sales">销售记录</el-menu-item>
                <!-- <el-menu-item index="distribution">库存分布</el-menu-item>
                <el-menu-item index="statistics">出入库统计</el-menu-item> -->
            </el-menu>
            <!-- 主内容区 -->
            <component :is="currentComponent" :details-data="pro.pro_code" :key="pro.pro_code" />
        </div>

        <!-- 底部操作按钮 -->
        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button @click="pro_handleClose">关闭</el-button>
        </div>
    </div>
</template>

<script>
import { ref, reactive, onMounted, watch, toRaw, markRaw, inject, computed } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { useRouter } from 'vue-router';
import { Delete, TurnOff } from '@element-plus/icons-vue'
import { useStore } from 'vuex';
import inventory from './ProductInfoPage_stock.vue'
import sales from './ProductInfoPage_sales.vue'
import purchase from './ProductInfoPage_purchase.vue'
import qty from './ProductInfoPage_qty.vue'
import trf from './ProductInfoPage_trf.vue'
export default {

    setup() {
        const fileList = ref([]); // 存储上传的文件列表
        const store = useStore()
        const activeIndex = ref('1')
        const data = ref([])
        const attributeOptios = ref([])
        const measureOptios = ref([])
        const router = useRouter()
        const activeMenu = ref('inventory')
        const stock_numder = ref(0)//库存数量
        const dict_code = ref("")//计量单位
        const pro_sale_total = ref()//库存金额
        const pro = reactive({
            pro_id: "",
            pro_name: "",//产品名称
            pro_code: "",//产品编号
            pro_type_code: "",//产品分类编号
            measure_id: "",//计量单位
            pro_attribute_id: "",//产品属性
            pro_model: "",//规格型号
            pro_sort: "",//产品排序
            pro_brand: "",//产品品牌
            pro_sale_price: "",//销售单价
            pro_cost_price: "",//成本单价
            pro_shelf_life: "",//产品保质期
            pro_grossMargin: "",//销售毛利
            pro_status: "0",//产品状态
            create_by: "",
            create_time: "",
            update_by: "",
            update_time: ""
        });

        const displayValue = (value) => {
            return value || '无';
        }

        onMounted(() => {
            pro_type_Opt()
            getAttribute()
            getMeasure()
            proFill()
        })

        function proFill() {
            const id = store.state.proCode
            axios.get("http://localhost:5181/api/Db_Product/GetDb_ProductByCode", {
                params: {
                    code: id
                }, headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }).then((result) => {
                for (const key in pro) {
                    pro[key] = String(result.data[key])
                    if (pro[key] == "") {
                        pro[key] = '暂无'
                    }
                }
                attFill(result.data.pro_code)
                getInv_Stock(result.data.pro_code)
            }).catch((err) => {
                console.info(err)
            });
        }

        function attFill(code) {
            axios.get("http://localhost:5181/api/Db_Attachmet/GetDb_Attachments", {
                params: {
                    code: code
                }, headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }).then((result) => {
                fileList.value = result.data
                fileList.value = result.data.map(item => ({
                    name: item.file_name,
                    url: item.file_address.startsWith('http')
                        ? item.file_address
                        : `http://localhost:5181${item.file_address}`, // 确保完整URL
                }));
            }).catch((err) => {
                console.info(err)
            });
        }

        function getInv_Stock(row) {
            axios.get("http://localhost:5181/api/Db_warehouse/GetInv_Stock", {
                params: {
                    productName: row,
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                stock_numder.value = computed(() => {
                    return result.data.reduce((total, row) => {
                        return total + (Number(row.stock_numder) || 0)
                    }, 0)
                })
                pro_sale_total.value = computed(() => {
                    return result.data.reduce((total, row) => {
                        return total + (Number(row.stock_numder * row.pro_cost_price) || 0)
                    }, 0)
                })
            }).catch((err) => {
                console.info(err)
            });
        }

        function pro_type_Opt() {
            axios.get("http://localhost:5181/api/Product_Type/GetProduct_Types", {
                params: {
                    currentPage: 0,
                    pageSize: 0,
                    typeName: "",
                    status: '0'
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                data.value = convertToTreeOptions(result.data)
            }).catch((err) => {
                console.info(err)
            });
        }

        const convertToTreeOptions = (items) => {
            return items.map(item => ({
                value: item.pro_type_code,
                pro_type_code: item.pro_type_code,
                label: item.pro_type_name,
                children: item.children && item.children.length > 0
                    ? convertToTreeOptions(item.children)
                    : []
            }))
        }

        function typeValue(code) {
            if (!code || !data.value) return "无";

            // 递归查找函数
            const findItemInTree = (items) => {
                for (const item of items) {
                    if (String(item.pro_type_code) === String(code)) {
                        return item;
                    }
                    if (item.children && item.children.length > 0) {
                        const found = findItemInTree(item.children);
                        if (found) return found;
                    }
                }
                return null;
            };

            const foundItem = findItemInTree(data.value);
            return foundItem ? foundItem.label : "无";
        }

        function getAttribute() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_pro_attribute"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                attributeOptios.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function attributeValue(row) {
            if (!row) return "无";
            const parentDept = attributeOptios.value.find((sex) => sex.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_measure"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                measureOptios.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function measureValue(row) {
            if (!row) return "无";
            const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        function handleEdit() {
            store.commit('proCode', pro.pro_code);
            router.push('/main/DB/ProductUpdate')
        }

        function handleDelete() {
            ElMessageBox.confirm(
                '此操作将删除' + pro.pro_name + '产品信息，是否继续？',
                '警告',
                {
                    type: 'warning',
                    icon: markRaw(Delete),
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }
            )
                .then(() => {
                    const loadingInstance = ElLoading.service({
                        lock: true,
                        text: '正在删除中...',
                        background: 'rgba(0, 0, 0, 0.7)',
                    });
                    axios.put("http://localhost:5181/api/Db_Product/ProductDel", {
                        pro_id: pro.pro_id,
                        del_flag: '1'
                    }, {
                        headers: {
                            authorization: `Bearer ${localStorage.getItem('token')}`
                        }
                    }).then((result) => {
                        if (result.data > 0) {
                            ElMessage.success('删除成功！')
                            router.push("/main/DB/ProductInfo");
                        }
                    }).catch((err) => {
                        console.info(err)
                    }).finally(() => {
                        loadingInstance.close();
                    })
                })
                .catch(() => {
                    ElMessage.info('已取消删除')
                })
        }

        function handleDeactivate() {
            ElMessageBox.confirm(
                '此操作将该产品停用，是否继续？',
                '警告',
                {
                    type: 'Info',
                    icon: markRaw(TurnOff),
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }
            )
                .then(() => {
                    axios.put("http://localhost:5181/api/Db_Product/ProductDeactivate", {
                        pro_id: pro.pro_id,
                        pro_status: '1'
                    }, {
                        headers: {
                            authorization: `Bearer ${localStorage.getItem('token')}`
                        }
                    }).then((result) => {
                        if (result.data > 0) {
                            ElMessage.info('修改成功！')
                            router.push("/main/DB/ProductInfo");
                        }
                    }).catch((err) => {
                        console.info(err)
                    });
                })
                .catch(() => {
                    ElMessage.info('已取消删除')
                })
        }

        const menuComponentMap = {
            inventory: inventory,
            // other: OtherInfo,
            // details: details,
            // outbound: outbound,
            purchase: purchase,
            sales: sales,
            qty: qty,
            trf: trf
            // visit: VisitRecord
        };

        const currentComponent = ref(inventory);

        const handleMenuSelect = (index) => {
            activeMenu.value = index;
            currentComponent.value = menuComponentMap[index];

            // 可以在此处添加数据加载逻辑
            // loadDataByMenu(index);
        };

        const closeTab = inject('closeTab'); // 注入关闭方法
        const pro_handleClose = () => {
            const targetPath = "/main/DB/ProductInfo";

            if (closeTab) {
                closeTab(); // 调用父组件提供的关闭方法
            }

            // 添加目标标签页（如果不存在）
            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "产品信息",
                    name: targetPath,
                    path: targetPath
                });
            }

            // 跳转并激活目标标签页
            const activeTab = inject('editableTabsValue');
            if (activeTab) {
                activeTab.value = targetPath;
            }

            router.push(targetPath);
        };

        return {
            fileList, activeIndex, pro, typeValue, data, measureValue, attributeOptios, measureOptios, attributeValue, displayValue, handleEdit,
            handleDelete, handleDeactivate, activeMenu, handleMenuSelect, pro_handleClose, stock_numder, dict_code, pro_sale_total,
            currentComponent
        }
    }
}
</script>

<style scoped>
.pro_info_title {
    text-align: center;
    width: 1205px;
    height: 40px;
}

.pro_info_value {
    /* margin-left: 260px; */
    transform: translateX(260px) translateY(-230px);
    /* position: relative;
    top: -230px;
    left: 260px; */
    width: 945px;
    height: 330px;
    background-color: aqua;
}

.pro_info_value2 {
    transform: translateX(0px) translateY(-300px);
    width: 230px;
    height: 70px;
}

.carousel-container {
    width: 100%;
    max-width: 230px;
    margin: 0 auto;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border-radius: 6px;
    overflow: hidden;
}

.carousel-image {
    width: 100%;
    height: 230px;
    object-fit: contain;
    display: block;
    background-color: #f5f7fa;
}

.draggable-item {
    transition: all 0.3s;
}

.dragging {
    opacity: 0.5;
    transform: scale(0.95);
}

.drag-over {
    outline: 2px dashed #409eff;
    outline-offset: 5px;
}

.goods-add-form {
    padding: 20px;
    background-color: #fff;
}

.section {
    padding: 20px;
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section1 {
    padding: 20px;
    height: 390px;
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
}

.inner-form {
    background-color: #fff;
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}

.img-title {
    /* display: flex;
    left: 60px; */
    margin-left: -390px;
    color: #99b3d4;
    font-size: 15px;
}
</style>